﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace 窗口载入窗口
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // MessageT T = new MessageT();

        // 页面缓存字典
        private readonly Dictionary<Type, Page> _pageCache = new Dictionary<Type, Page>();

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // EToolsFrame.Navigate(new Tools());
            // new windows1().Show();
            // ContentArea.Content = this.T;
            NavigateToPage(typeof(Tools));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //EToolsFrame.Navigate(new Tools());
            // EToolsFrame.Navigate(new Page02());
            NavigateToPage(typeof(Page02));
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            // EToolsFrame.Navigate(new Tools());
            NavigateToPage(typeof(Tools));
        }

        // 通用页面切换方法
        private void NavigateToPage(Type pageType)
        {
            // 检查当前显示的页面是否与目标页面相同
            if (this.EToolsFrame.Content is Page currentPage && currentPage.GetType() == pageType)
            {
                // 当前页面已经是目标页面，不进行导航
                return;
            }

            if (!_pageCache.TryGetValue(pageType, out Page page))
            {
                // 如果没有缓存则创建新实例并添加到缓存
                page = (Page)Activator.CreateInstance(pageType);
                _pageCache[pageType] = page;
            }

            // EToolsFrame.Navigate(page);
            NavigateWithAnimation(page);
        }

        private void EToolsFrame_ContentRendered(object sender, EventArgs e)
        {
            // 每次内容渲染完成后，触发淡入动画
            // var fadeInAnimation = (Storyboard)FindResource("FadeInStoryboard");
            // fadeInAnimation.Begin(EToolsFrame);

            // 切换界面，缓动向上平移动画
            var fadeInAnimation = (Storyboard)FindResource("SlideUpStoryboard");
            fadeInAnimation.Begin(EToolsFrame);
        }

        private async void NavigateWithAnimation(Page newPage)
        {
            // 渐隐动画
            var fadeOutAnimation = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(200));
            EToolsFrame.BeginAnimation(OpacityProperty, fadeOutAnimation);

            // 等待动画完成
            await Task.Delay(200);

            // 切换页面
            EToolsFrame.Navigate(newPage);

            // 渐显动画
            var fadeInAnimation = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(200));
            EToolsFrame.BeginAnimation(OpacityProperty, fadeInAnimation);
        }
    }
}
